package com.cloudfun.campusshare.configuration.config;

import com.cloudfun.campusshare.common.model.vo.AuthOrgVO;
import com.cloudfun.campusshare.common.model.vo.ImageVo;
import com.cloudfun.campusshare.entity.AttachmentEntity;
import com.cloudfun.campusshare.service.AttachmentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@ControllerAdvice
public class Binder {

    @Autowired
    private AttachmentService attachmentService;

    @InitBinder
    public void init(WebDataBinder webDataBinder) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        request.setAttribute("target", webDataBinder.getTarget());
    }

    public void setUrl(ImageVo vo){
        if (vo==null){
            return;
        }
        AttachmentEntity attach = attachmentService.getAttach(vo.getId());
        vo.setUrl(attach.getUrl());
        vo.setName(attach.getName());
    }
}
